package com.springcloud.sc.ucpv5.client.util;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;

public class TextUtil {
	public TextUtil() {
	}

	/**
	 * relace line with a new line.first find this line according a tag str,
	 * then relace it to the line end with the new linevalue
	 * 
	 * @param[in] fileName the ascii file name
	 * @param[in] tagStr the tag string that can identify the line in the file
	 * @param[in] lineValue the new value
	 */
	public static void replaceLine(String fileName, String tagStr, String lineValue) {
		String datastr = getFileContents(fileName);
		String resultstr = parseStr(datastr, tagStr, lineValue);
		writeFile(fileName, resultstr);
	}

	public static String getFileContents(String fileName) {
		try {
			// Open a file of the given name.
			File file = new File(fileName);
			// Get the size of the opened file.
			int size = (int) file.length();
			// Set to zero a counter for counting the number of
			// characters that have been read from the file.
			int chars_read = 0;
			// Create an input reader based on the file, so we can read its
			// data.
			// FileReader handles international character encoding conversions.
			FileReader in = new FileReader(file);
			// Create a character array of the size of the file,
			// to use as a data buffer, into which we will read
			// the text data.
			char[] data = new char[size];
			// Read all available characters into the buffer.
			while (in.ready()) {
				// Increment the count for each character read,
				// and accumulate them in the data buffer.
				chars_read += in.read(data, chars_read, size - chars_read);
			}
			in.close();
			String datastr = new String(data);
			// trim EOF char
			datastr = datastr.substring(0, datastr.length() - 1);
			if (!datastr.substring(datastr.length() - 1).equals("\n")) {
				datastr = datastr + "\n";
			}
			return datastr;
		} catch (IOException e) {
			// DebugTracer.trace ( "Error opening " + fileName ) ;
		}
		return null;
	}

	/**
	 * find a value for a tag str
	 * 
	 * @param datastr
	 *            content
	 * @param tagstr
	 *            the tag str
	 * @return the value,from tagstr to the end of this line
	 */
	public static String findTagValue(String datastr, String tagstr) {
		int startindex = datastr.indexOf(tagstr);
		int endindex = 0;
		// find the the end of the line
		for (int i = startindex + tagstr.length(); i < datastr.length(); i++) {
			String ch = datastr.substring(i, i + 1);
			endindex = i;
			if (ch.equals("\n")) {
				break;
			}
		}
		// if cannot find this tag,then insert it in the first line
		if (startindex < 0 || startindex > endindex) {
			return "";
		}
		return datastr.substring(startindex + tagstr.length(), endindex);
	}

	/**
	 * parse line,handle the line with new value
	 * 
	 * @param datastr
	 *            an original line
	 * @param tagstr
	 *            tag str
	 * @param lineValue
	 *            new value
	 * @return
	 */
	private static String parseStr(String datastr, String tagstr, String lineValue) {
		int startindex = datastr.indexOf(tagstr);
		int endindex = 0;
		// find the the end of the line
		for (int i = startindex + tagstr.length(); i < datastr.length(); i++) {
			if (datastr.substring(i, i + 1).equals("\n")) {
				endindex = i;
				break;
			}
		}
		// if cannot find this tag,then insert it in the first line
		if (startindex < 0) {
			// DebugTracer.trace ( "cannot find this tag:" + tagstr ) ;
			startindex = 0;
			endindex = 0;
		}
		String prefixLines = datastr.substring(0, startindex);
		String postLines = datastr.substring(endindex, datastr.length());
		return prefixLines + lineValue + postLines;
	}

	/**
	 * Save current file with string
	 * 
	 * @param currFileName
	 *            the file name
	 * @param strline
	 *            file contents
	 * @return
	 */
	private static boolean writeFile(String currFileName, String strline) {
		try {
			// Open a file of the current name.
			File file = new File(currFileName);
			// Create an output writer that will write to that file.
			// FileWriter handles international characters encoding conversions.
			FileWriter out = new FileWriter(file);
			out.write(strline);
			out.flush();
			out.close();
			return true;
		} catch (IOException e) {
			// DebugTracer.trace ( "Error saving " + currFileName ) ;
		}
		return false;
	}

	/**
	 * parst String to String[], 1.2.3 -> array[]
	 * 
	 * @param domainstr
	 * @return the domain name in [] format
	 */
	public static String[] parseDomainStr(String domainstr) {
		LinkedList<String> domains = new LinkedList<String>();
		int lastIndex = 0;
		for (int i = 0; i < domainstr.length(); i++) {
			if (domainstr.charAt(i) == '.') {
				domains.add(domainstr.substring(lastIndex, i));
				lastIndex = i + 1;
			}
		}
		domains.add(domainstr.substring(lastIndex, domainstr.length()));
		String[] domainArray = new String[domains.size()];
		int j = 0;
		for (Iterator it = domains.iterator(); it.hasNext();) {
			domainArray[j] = (String) it.next();
			j++;
		}
		return domainArray;
	}
}
